package com.tuzhi.sys.scurity.impl;

import com.tuzhi.base.jpa.healper.QueryHelper;
import com.tuzhi.base.jpa.healper.wenhao.TPredicateBuilder;
import com.tuzhi.base.jpa.healper.wenhao.TSpecifications;
import com.tuzhi.base.web.config.SecurityConfig;
import com.tuzhi.base.web.interceptor.RSAConfig;
import com.tuzhi.common.exception.BusinessException;
import com.tuzhi.config.ConstantConfig;
import com.tuzhi.sys.dto.SysMenuTreeDto;
import com.tuzhi.sys.jpa.entity.*;
import com.tuzhi.sys.jpa.repository.SysAuthRepo;
import com.tuzhi.sys.scurity.AuthService;
import com.tuzhi.sys.service.*;
import com.tuzhi.util.CollectionsTzUtil;
import com.tuzhi.util.RSAUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.mindrot.jbcrypt.BCrypt;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import java.util.*;

import static com.tuzhi.config.ConstantConfig.ALL_PERMISSION;
import static com.tuzhi.config.ConstantConfig.SYS_USER_DEFAULT_PASSWORD;

@Service
@Slf4j
public class AuthServiceImpl implements AuthService {
    @Autowired
    SysUserService userService;
    @Autowired
    SysMenuService menuService;
    @Autowired
    SysRoleService roleService;
    @Autowired
    SysUserRoleService userRoleService; //用户与角色
    @Autowired
    SysRoleMenuService roleMenuService;//角色与菜单
    @Autowired
    UserRoleMenuViewService userRoleMenuService;//用户-角色-菜单 视图

    @Autowired
    RoleMenuViewService roleMenuViewService; //角色-菜单 视图

    @Autowired
    UserRoleViewService userRoleViewService;

    @Autowired
    AuthCacheService authCacheService;

    @Autowired
    SysAuthService sysAuthService;

    @Autowired
    SysDictionaryService sysDictionaryService;
    @Autowired
    SecurityConfig securityConfig;

    /**
     * 超级管理员的角色Id
     */
    static Long super_role_id;

    /**
     * 企业管理员的角色Id
     */
    static Long enterprise_role_id;

    static final AntPathMatcher pathMatcher = new AntPathMatcher();


    @Override
    public List<String> loadPerms4User(Long userId) {
        if (superAdmin(userId)) {
            //超管返回全部权限
            return menuService.loadAllPerms();
        }
        return userRoleMenuService.loadPerms4User(userId);
    }

    @Override
    public List<String> loadPerms4Role(Long roleId) {
        if (getSuperRoleId().intValue() == roleId.intValue()) {
            //超管返回全部权限
            return menuService.loadAllPerms();
        }
        return roleMenuViewService.loadPerms4Role(roleId);
    }

    @Override
    public List<String> loadPerms4Role(String roleName) {
        if (ConstantConfig.SUPER_ROLE_NAME.equals(roleName)) {
            //超管返回全部权限
            return menuService.loadAllPerms();
        }
        return roleMenuViewService.loadPerms4Role(roleName);
    }

    @Override
    public List<String> loadUrls4User(Long userId) {
        if (superAdmin(userId)) {
            //超管返回全部权限
            return menuService.loadAllUrls();
        }
        return userRoleMenuService.loadUrls4User(userId);
    }

    @Override
    public List<String> loadUrls4Role(Long roleId) {
        if (getSuperRoleId().intValue() == roleId.intValue()) {
            //超管返回全部权限
            return menuService.loadAllUrls();
        }
        return roleMenuViewService.loadUrls4Role(roleId);
    }

    @Override
    public List<String> loadUrls4Role(String roleName) {
        if (ConstantConfig.SUPER_ROLE_NAME.equals(roleName)) {
            //超管返回全部权限
            return menuService.loadAllUrls();
        }
        return roleMenuViewService.loadUrls4Role(roleName);
    }

    @Override
    public List<Long> loadRoleIds(Long userId) {
        return userRoleService.listRoleId4UserId(userId);
    }

    @Override
    public List<String> loadRoleNames(Long userId) {
        List<UserRoleViewEntity> userRoleViewList = userRoleViewService.findByUserId(userId);
        if (CollectionUtils.isNotEmpty(userRoleViewList)) {
            List<String> roleNames = new ArrayList<>(userRoleViewList.size());
            for (UserRoleViewEntity entity : userRoleViewList) {
                roleNames.add(entity.getRoleName());
            }
            return roleNames;
        }
        return null;
    }

    @Override
    public List<Long> loadMenus(Long userId) {
        return userRoleMenuService.findMenuIds(userId);
    }

    @Override
    public List<Long> LoadMenuId4Role(Long roleId) {
        return roleMenuService.listMenuId4Role(roleId);
    }


    public List<Long> getSysAuthId(Long roleId) {

        return sysAuthService.getAuthIds(roleId);
    }

    @Override
    public void saveUserRole(Long userId, Collection<Long> roleIds) {
        userRoleService.saveUserRole(userId, roleIds);
        Collection<String> roleIds4Cache = authCacheService.findUserRoleNameCache(userId);
        if (roleIds4Cache != null) {
            List<String> roleNames = loadRoleNames(userId);
            authCacheService.setUserRoles2Cache(userId, roleNames);
        }
    }

    @Override
    public void saveUserRoleByName(Long userId, Collection<String> roleNames) {
        Set<Long> roleIdSet = userService.roleName2RoleIds(roleNames);
        userRoleService.saveUserRole(userId, roleIdSet);
        Collection<String> roleIds4Cache = authCacheService.findUserRoleNameCache(userId);
        if (roleIds4Cache != null) {
            authCacheService.setUserRoles2Cache(userId, roleNames);
        }
    }


    @Override
    public void savePerms4Role(Long roleId, Collection<Long> menuIds) {
        List<Long> dbIds = LoadMenuId4Role(roleId);
        //查出要新增的项
        Collection<Long> addIds = CollectionsTzUtil.getAddItem(dbIds, menuIds);
        for (Long menuId : addIds) {
            SysRoleMenuEntity roleMenu = new SysRoleMenuEntity();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuService.save(roleMenu);
        }
        //查出要删除的项
        Collection<Long> deleteIds = CollectionsTzUtil.getDeleteItem(dbIds, menuIds);
        for (Long menuId : deleteIds) {
            SysRoleMenuEntity roleMenu = new SysRoleMenuEntity();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenuService.delete(roleMenu);
        }
        SysRoleEntity roleEntity = roleService.findById(roleId);
        List<Long> menus4Cache = authCacheService.findRoleMenuIdsCache(roleEntity.getName());
        if (menus4Cache != null) {
            authCacheService.setRoleMenus2Cache(roleId, menuIds);
        }
        //把权限标识缓存也更新
        List<String> perms = loadPerms4Role(roleId);
        authCacheService.setRolePerms2Cache(roleEntity.getName(), perms);
    }

    @Override
    public boolean hasPerm4Role(Long roleId, String perm) {
        SysRoleEntity roleEntity = roleService.findById(roleId);
        return hasPerm4Role(roleEntity.getName(), perm);
    }

    @Override
    public boolean hasPerm4Role(String roleName, String perm) {
        Collection<String> perms = findRolePerms4CacheAndDb(roleName);
        if (ConstantConfig.SUPER_ROLE_NAME.equals(roleName)) {
            return true;
        }
        return CollectionUtils.isNotEmpty(perms) && perms.contains(perm);
    }

    @Override
    public boolean hasPerm4User(Long userId, String perm) {
        Collection<String> perms = findUserPerms4CacheAndDb(userId);
        if (superAdmin(userId)) {
            return true;
        }
        return CollectionUtils.isNotEmpty(perms) && perms.contains(perm);
    }

    /**
     * 查找角色 权限标识:先从缓存中找，没有再从数据库中找
     *
     * @param roleName
     * @return
     */
    @Override
    public Collection<String> findRolePerms4CacheAndDb(String roleName) {
        Collection<String> perms = authCacheService.findRolePermsCache(roleName);//从缓存中查找
        if (CollectionUtils.isEmpty(perms)) {
            //从数据库加载权限
            perms = loadPerms4Role(roleName);
            if (CollectionUtils.isNotEmpty(perms)) {
                authCacheService.setRolePerms2Cache(roleName, perms);
            }
        }
        return perms;
    }


    /**
     * 查找角色 url :先从缓存中找，没有再从数据库中找
     *
     * @param roleName
     * @return
     */
    @Override
    public Collection<String> findRoleUrls4CacheAndDb(String roleName) {
        Collection<String> urls = authCacheService.findRoleUrlsCache(roleName);//从缓存中查找
        if (CollectionUtils.isEmpty(urls)) {
            //从数据库加载权限
            urls = loadUrls4Role(roleName);
            if (CollectionUtils.isNotEmpty(urls)) {
                authCacheService.setRolePerms2Cache(roleName, urls);
            }
        }
        return urls;
    }


    /**
     * 查找用户 权限标识:先从缓存中找，没有再从数据库中找
     *
     * @param userId
     * @return
     */
    @Override
    public Collection<String> findUserPerms4CacheAndDb(Long userId) {
        Collection<String> roleNameList = findUserRoleName4CacheAndDb(userId);
        if (CollectionUtils.isNotEmpty(roleNameList)) {
            Set<String> perms = new HashSet<>();
            for (String roleName : roleNameList) {
                Collection<String> perms4Role = findRolePerms4CacheAndDb(roleName);
                if (CollectionUtils.isNotEmpty(perms4Role)) {
                    perms.addAll(perms4Role);
                }
            }
            return new ArrayList<>(perms);
        }
        return null;
    }


    /**
     * 查找用户 url:先从缓存中找，没有再从数据库中找
     *
     * @param userId
     * @return
     */
    @Override
    public Collection<String> findUserUrls4CacheAndDb(Long userId) {
        Collection<String> roleNameList = findUserRoleName4CacheAndDb(userId);
        if (CollectionUtils.isNotEmpty(roleNameList)) {
            Set<String> urlSet = new HashSet<>();
            for (String roleName : roleNameList) {
                Collection<String> perms4Role = findRoleUrls4CacheAndDb(roleName);
                if (CollectionUtils.isNotEmpty(perms4Role)) {
                    urlSet.addAll(perms4Role);
                }
            }
            return new ArrayList<>(urlSet);
        }
        return null;
    }


    /**
     * 查找用户角色:先从缓存中找，没有再从数据库中找
     *
     * @param userId
     * @return
     */
    @Override
    public Collection<String> findUserRoleName4CacheAndDb(Long userId) {
        Collection<String> roleNames = authCacheService.findUserRoleNameCache(userId);//从缓存中查找
        if (CollectionUtils.isEmpty(roleNames)) {
            //从数据库加载权限
            roleNames = loadRoleNames(userId);
            if (CollectionUtils.isNotEmpty(roleNames)) {
                authCacheService.setUserRoles2Cache(userId, roleNames);
            }
        }
        return roleNames;
    }

    @Transactional
    @Override
    public void deleteUser(Long userId) {
        userService.deleteById(userId);
        userRoleService.deleteByUserId(userId);
        authCacheService.delUserRoleNameCache(userId);
    }

    @Transactional
    @Override
    public void deleteRole(Long roleId) {
        SysRoleEntity roleEntity = roleService.findById(roleId);
        roleService.deleteById(roleId);
        userRoleService.deleteByRoleId(roleId);
        roleMenuService.deleteByRoleId(roleId);
        authCacheService.delRolePermsCache(roleEntity.getName());
        authCacheService.delMenuIdsCache(roleEntity.getName());
        authCacheService.delRoleUrlsCache(roleEntity.getName());
    }

    @Transactional
    @Override
    public void deleteMenu(Long menuId) {
        menuService.deleteById(menuId);
        roleMenuService.deleteByMenuId(menuId);
        authCacheService.deleteRolePermsCache();
        authCacheService.deleteRoleUrlsCache();
    }

    @Override
    public void saveMenu(SysMenuEntity menuEntity) {
        menuService.save(menuEntity);
        authCacheService.deleteRolePermsCache();
        authCacheService.deleteRoleUrlsCache();
    }

    /**
     * 查找菜单树，并将指定角色的权限标记
     *
     * @param roleId
     * @return
     */
    @Override
    public List<SysMenuTreeDto> loadAllMenuTree4Role(Long roleId) {
        List<SysMenuTreeDto> menuTreeDtos = menuService.loadAllMenuTree();
        if (CollectionUtils.isNotEmpty(menuTreeDtos)) {
            SysRoleEntity roleEntity = roleService.findById(roleId);
            Collection<String> rolePerms = findRolePerms4CacheAndDb(roleEntity.getName());
            hasPerm4RoleFLag(menuTreeDtos, roleId, rolePerms);
        }
        return menuTreeDtos;
    }

    @Override
    public List<SysMenuTreeDto> loadAllMenuTree4RoleBaseOpUser(Long roleId, Long userId) {
        List<SysMenuTreeDto> menuTreeDtos = menuService.loadAllMenuTree();
        Collection<String> perms4User = findUserPerms4CacheAndDb(userId);
        SysRoleEntity roleEntity = roleService.findById(roleId);
        Collection<String> perms4Role = findRolePerms4CacheAndDb(roleEntity.getName());
        Collection<String> perms4All = new HashSet<>();
        if (CollectionUtils.isNotEmpty(perms4User)) {
            perms4All.addAll(perms4User);
        }
        if (CollectionUtils.isNotEmpty(perms4Role)) {
            perms4All.addAll(perms4Role);
        }
        hasPermDel(menuTreeDtos, perms4All);
        hasPerm4RoleFLag(menuTreeDtos, roleId, perms4Role);
        return menuTreeDtos;
    }

    @Override
    public List<SysMenuTreeDto> loadUserMenuTree(Long userId) {
        List<SysMenuTreeDto> menuTreeDtos = menuService.loadAllMenuTree();
        if (CollectionUtils.isNotEmpty(menuTreeDtos)) {
            Collection<String> userPerms = findUserPerms4CacheAndDb(userId);
            hasPerm4RoleFLag(menuTreeDtos, userId, userPerms);
        }
        return menuTreeDtos;
    }

    @Override
    public List<SysMenuTreeDto> loadUserMenuTreeOnly(Long userId) {
        List<SysMenuTreeDto> menuTreeDtos = menuService.loadAllMenuTree();
        Collection<String> perms = findUserPerms4CacheAndDb(userId);
        hasPerm4User(menuTreeDtos, userId, perms);
        return menuTreeDtos;
    }

    @Override
    public boolean superAdmin(Long userId) {
        Collection<String> roleNames = findUserRoleName4CacheAndDb(userId);
        return CollectionUtils.isNotEmpty(roleNames) && roleNames.contains(ConstantConfig.SUPER_ROLE_NAME);
    }

    @Override
    public boolean enterpriseAdmin(Long userId) {
        Collection<String> roleNames = findUserRoleName4CacheAndDb(userId);
        return CollectionUtils.isNotEmpty(roleNames) && roleNames.contains(ConstantConfig.ENTERPRISE_MANAGER_ROLE_NAME);
    }

  /*  @Override
    public boolean hasPerm4User(Long userId, String perm) {
        Collection<String> perms = findUserPerms4CacheAndDb(userId);
        *//*return perms.stream().filter(StringUtils::hasText)
                .anyMatch(x -> ALL_PERMISSION.equals(x) || PatternMatchUtils.simpleMatch(x, perm));*//*
        return perms.stream().filter(StringUtils::hasText)
                .anyMatch(x -> ALL_PERMISSION.equals(x) || pathMatcher.match(x, perm));
    }*/

    @Override
    public boolean hasUri4User(Long userId, String url) {
        Collection<String> urls = findUserUrls4CacheAndDb(userId);
       /* return urls.stream().filter(StringUtils::hasText)
                .anyMatch(x -> ALL_PERMISSION.equals(x) || PatternMatchUtils.simpleMatch(x, url));*/
        if (superAdmin(userId)) {
            return true;
        }
        return urls.stream().filter(StringUtils::hasText)
                .anyMatch(x -> ALL_PERMISSION.equals(x) || pathMatcher.match(x, url));
    }

    @Override
    public SysUserEntity saveUserAndRole(SysUserEntity sysUserEntity) {

        if (sysUserEntity == null) {
            throw new BusinessException("提交内容不能为空");
        }
        if (sysUserEntity.getId() == null) {
            SysUserEntity entity = userService.getOneUnique(SysUserEntity::getUsername, sysUserEntity.getUsername());
            if (entity != null) {
                throw new BusinessException(String.format("帐号己存在：%s", entity.getUsername()));
            }
            entity = userService.getOneUnique(SysUserEntity::getNickname, sysUserEntity.getNickname());
            if (entity != null) {
                throw new BusinessException(String.format("Nickname己存在 不能重复：%s", entity.getUsername()));
            }
            if (org.apache.commons.lang3.StringUtils.isBlank(sysUserEntity.getPassword())) {
                sysUserEntity.setPassword(SYS_USER_DEFAULT_PASSWORD);
            }
            String newPwd_ = BCrypt.hashpw(sysUserEntity.getPassword(), BCrypt.gensalt());
            sysUserEntity.setPassword(newPwd_);
            SysUserEntity entity1 = userService.save(sysUserEntity);
            saveUserRoleByName(entity1.getId(), sysUserEntity.getRoles());
//            authCacheService.setUserRoles2Cache(entity1.getId(), sysUserEntity.getRoles());
            return entity1;
        } else {
            QueryHelper.Builder<SysUserEntity> builder = new QueryHelper.Builder<>();
            builder.neq(SysUserEntity::getUsername, sysUserEntity.getUsername());
            builder.eq(SysUserEntity::getNickname, sysUserEntity.getNickname());
            List<SysUserEntity> list = userService.findAllByWhereConditionBO(builder.build().getWhereConditionBO());
            if (list != null && list.size() > 0) {
                throw new BusinessException(String.format("Nickname己存在 不能重复：%s", sysUserEntity.getUsername()));
            }
            SysUserEntity loadDbEntity = userService.getOneUnique(SysUserEntity::getUsername, sysUserEntity.getUsername());
            if (org.apache.commons.lang3.StringUtils.isNotBlank(sysUserEntity.getPassword())) {
                String newPwd_ = BCrypt.hashpw(sysUserEntity.getPassword(), BCrypt.gensalt());
                loadDbEntity.setPassword(newPwd_);
            }
            loadDbEntity.setNickname(sysUserEntity.getNickname());
            loadDbEntity.setOrgId(sysUserEntity.getOrgId());
            loadDbEntity.setPhone(sysUserEntity.getPhone());
            loadDbEntity.setEmail(sysUserEntity.getEmail());
//            Set<Long> roleIdSet = userService.roleName2RoleIds(sysUserEntity.getRoles());
//            userRoleService.saveUserRole(loadDbEntity.getId(), roleIdSet);
            saveUserRoleByName(loadDbEntity.getId(), sysUserEntity.getRoles());
            userService.save(loadDbEntity);
//            authCacheService.setUserRoles2Cache(loadDbEntity.getId(), sysUserEntity.getRoles());
            return loadDbEntity;
        }
    }

    @Override
    public List<SysRoleEntity> listRoles4UserName(String userName) {
        return userService.listRoles4UserName(userName);
    }

    /**
     * 标记角色是否有权限
     *
     * @param menuTreeDtos
     * @param roleId
     */
    private void hasPerm4RoleFLag(List<SysMenuTreeDto> menuTreeDtos, Long roleId, Collection<String> rolePerms) {
        if (CollectionUtils.isNotEmpty(menuTreeDtos)) {
            for (SysMenuTreeDto dto : menuTreeDtos) {
                if (CollectionUtils.isNotEmpty(rolePerms)) {
                    if (rolePerms.contains(dto.getPerms())) {
                        dto.setExitsPerm(true);
                    }
                } else {
                    if (hasPerm4Role(roleId, dto.getPerms())) {
                        dto.setExitsPerm(true);
                    }
                }
                if (CollectionUtils.isNotEmpty(dto.getChildMenus())) {
                    hasPerm4RoleFLag(dto.getChildMenus(), roleId, rolePerms);
                }
            }
        }
    }

    /**
     * 删除没有的权限
     *
     * @param menuTreeDtos
     */
    private void hasPermDel(List<SysMenuTreeDto> menuTreeDtos, Collection<String> perms) {
        if (CollectionUtils.isNotEmpty(menuTreeDtos)) {
            Iterator<SysMenuTreeDto> iterator = menuTreeDtos.listIterator();
            while (iterator.hasNext()) {
                SysMenuTreeDto dto = iterator.next();
                if (CollectionUtils.isNotEmpty(perms)) {
                    if (!perms.contains(dto.getPerms())) {
                        iterator.remove();
                        continue;
                    }
                }
                if (CollectionUtils.isNotEmpty(dto.getChildMenus())) {
                    hasPermDel(dto.getChildMenus(), perms);
                }
            }
        }
    }

    /**
     * 传入菜单树，用户ID，用户权限集合（可不传），移除没有权限的项目，返回整个有权限的菜单树
     *
     * @param menuTreeDtos
     * @param userId
     * @param userPerms
     */
    private void hasPerm4User(List<SysMenuTreeDto> menuTreeDtos, Long userId, Collection<String> userPerms) {
        if (CollectionUtils.isNotEmpty(menuTreeDtos)) {
            Iterator<SysMenuTreeDto> iterator = menuTreeDtos.listIterator();
            while (iterator.hasNext()) {
                SysMenuTreeDto dto = iterator.next();
                if (CollectionUtils.isNotEmpty(userPerms)) {
                    if (!userPerms.contains(dto.getPerms())) {
                        iterator.remove();
                        continue;
                    }
                } else {
                    if (!hasPerm4User(userId, dto.getPerms())) {
                        iterator.remove();
                        continue;
                    }
                }
                dto.setExitsPerm(true);
                if (CollectionUtils.isNotEmpty(dto.getChildMenus())) {
                    hasPerm4User(dto.getChildMenus(), userId, userPerms);
                }
            }

        }
    }


    /**
     * 获取超级管理员角色Id
     *
     * @return
     */
    private Long getSuperRoleId() {
        if (super_role_id == null) {
            TPredicateBuilder<SysRoleEntity> queryBuilder = TSpecifications.and();
            queryBuilder.eq(SysRoleEntity::getName, ConstantConfig.SUPER_ROLE_NAME);
            SysRoleEntity roleEntity = roleService.getOneUnique(queryBuilder.build());
            if (roleEntity != null) {
                super_role_id = roleEntity.getId();
            }
        }
        return super_role_id;
    }

    /**
     * 获取企业管理员角色Id
     *
     * @return
     */
    private Long getEnterpriseRoleId() {
        if (enterprise_role_id == null) {
            TPredicateBuilder<SysRoleEntity> queryBuilder = TSpecifications.and();
            queryBuilder.eq(SysRoleEntity::getName, ConstantConfig.ENTERPRISE_MANAGER_ROLE_NAME);
            SysRoleEntity roleEntity = roleService.getOneUnique(queryBuilder.build());
            if (roleEntity != null) {
                enterprise_role_id = roleEntity.getId();
            }
        }
        return enterprise_role_id;
    }

    @Autowired
    SysMenuService sysMenuService;

    @Autowired
    SysAuthRepo sysAuthRepo;

    @Transactional
    @Override
    public void saveRoleAuth(Long roleId, List<Long> menuIds) {
        SysRoleEntity sysRoleEntity = roleService.get(roleId);
//        //获取角色旧的菜单id
//        List<Long>  Ids = getSysAuthId(roleId);
//        //查出新增项
//        Collection<Long> addIds = CollectionsTzUtil.getAddItem(Ids, menuIds);
//        for (Long menuId : addIds) {
//            SysMenuEntity sysMenuEntity = sysMenuService.get(menuId);
//            SysAuthEntity sysAuth = new SysAuthEntity();
//            sysAuth.setResourceId(menuId);
//            sysAuth.setResourceName(sysMenuEntity.getTitle());
//            sysAuth.setResourceType(SysAuthEntity.ResourceType.Menu.getValue());
//            sysAuth.setAuthId(roleId);
//            sysAuth.setAuthName(sysRoleEntity.getName());
//            sysAuth.setAuthType(SysAuthEntity.Type.ROLE.getValue());
//            sysAuthService.save(sysAuth);
//        }
        for (Long menuId : menuIds) {
            SysMenuEntity sysMenuEntity = sysMenuService.get(menuId);
            SysAuthEntity sysAuth = new SysAuthEntity();
            sysAuth.setResourceId(menuId);
            sysAuth.setResourceName(sysMenuEntity.getTitle());
            sysAuth.setResourceType(SysAuthEntity.ResourceType.Menu.getValue());
            sysAuth.setAuthId(roleId);
            sysAuth.setAuthName(sysRoleEntity.getName());
            sysAuth.setAuthType(SysAuthEntity.Type.ROLE.getValue());
            sysAuthService.save(sysAuth);
        }
//        //查出要删除的项
//        Collection<Long> deleteIds = CollectionsTzUtil.getDeleteItem(Ids, menuIds);
//        for (Long menuId : deleteIds) {
//            SysAuthEntity sysAuth = new SysAuthEntity();
//            sysAuth.setResourceId(menuId);
//            sysAuth.setAuthId(roleId);
//            sysAuth.setResourceType(SysAuthEntity.ResourceType.Menu.getValue());
//            sysAuth.setAuthType(SysAuthEntity.Type.ROLE.getValue());
//            sysAuthService.delete(sysAuth);
//        }
        //删除旧的菜单权限
        SysAuthEntity sysAuth = new SysAuthEntity();
        sysAuth.setAuthId(roleId);
        sysAuth.setResourceType(SysAuthEntity.ResourceType.Menu.getValue());
        sysAuth.setAuthType(SysAuthEntity.Type.ROLE.getValue());
        sysAuthService.delete(sysAuth);

        List<Long> menus4Cache = authCacheService.findRoleMenuIdsCache(sysRoleEntity.getName());
        if (menus4Cache != null) {
            // 设置角色的菜单Id缓存
            authCacheService.setRoleMenus2Cache(roleId, menuIds);
        }
        //把权限标识缓存也更新
        List<String> menuPerms = getMenuPerms(roleId);
        authCacheService.setRolePerms2Cache(sysRoleEntity.getName(), menuPerms);
    }

    private List<String> getMenuPerms(Long roleId) {
        if (getSuperRoleId().intValue() == roleId.intValue()) {
            //超管返回全部权限
            return menuService.loadAllPerms();
        } else {
            QueryHelper.Builder<SysAuthEntity> builder = new QueryHelper.Builder<>();
            builder.eq(SysAuthEntity::getAuthId, roleId);
            builder.eq(SysAuthEntity::getAuthType, SysAuthEntity.Type.ROLE.getValue());
            builder.eq(SysAuthEntity::getResourceType, SysAuthEntity.ResourceType.Menu.getValue());
            List<SysAuthEntity> menuAuth = sysAuthRepo.findAll(builder.build().getWhereConditionBO());
            List<String> perms = new ArrayList<>();
            menuAuth.forEach(sysAuth -> {
                SysMenuEntity sysMenuEntity = menuService.get(sysAuth.getResourceId());
                if (null != sysMenuEntity) {
                    perms.add(sysMenuEntity.getPerms());
                }
            });
            return perms;
        }
    }

    /**
     * 获取不需要鉴权的地址
     *
     * @return
     */
    public Set<String> getNotAuthUrl() {
        try {
            Set<String> notAuthUrl = authCacheService.findNotAuthUrl();
            if (notAuthUrl != null && !notAuthUrl.isEmpty()) {
                return notAuthUrl;
            } else {
                List<SysDictionaryEntity> list = sysDictionaryService.listEntityOfDicName("notAuthUrl");
                if (list != null && !list.isEmpty()) {
                    for (SysDictionaryEntity item : list) {
                        notAuthUrl.add(item.getDicValue());
                    }
                    authCacheService.setNotAuthUrl(notAuthUrl);
                }
                return notAuthUrl;
            }
        } catch (Exception ex) {

            log.error("加载不校验的URL资源出错。。{}", ExceptionUtils.getStackTrace(ex));
        }
        return null;
    }

    /**
     * 不鉴权地址允许防问
     *
     * @param url
     * @return
     */
    public boolean isPermitUri4NoAuthUrl(String url) {
        if (securityConfig.isPermitUri4NoAuthUrl(url)) {
            //配置文件中的不鉴权地址
            return true;
        }
        //数据库表中的
        Set<String> notAuthUrlList = getNotAuthUrl();
        if (CollectionUtils.isNotEmpty(notAuthUrlList)) {
            return notAuthUrlList.stream().filter(StringUtils::hasText)
                    .anyMatch(x -> ALL_PERMISSION.equals(x) || pathMatcher.match(x, url));
        }
        return false;
    }

    @Override
    public boolean verifySignature(String sign, Long timestamp) {
        if (org.apache.commons.lang3.StringUtils.isBlank(sign) || timestamp == null) {
            return false;
        }
        String publicKeyStr = RSAConfig.getPublicKey();
        String singStr = securityConfig.getSignCode() + "-" + timestamp;
        boolean result = RSAUtil.verify(singStr.getBytes(), sign, publicKeyStr);
        if (result) {
            long currentTime = System.currentTimeMillis();
            if (Math.abs(currentTime - timestamp) > securityConfig.getTimestampTolerance()) {
                return false; // 时间戳不在容忍范围内
            }
        }
        return result;
    }


}
